import time
import tkinter as tk
import threading

from bases.windows import test_time_var


class TimeLabel(tk.Label):
    def __init__(self, master, event:threading.Event,boolVar:tk.BooleanVar, **kwargs):
        """
        用于计时的label
        :param master: 主界面
        :param event: 传入一个多线程事件对象，用于暂停子线程，等待主线程唤醒
        :param boolVar: 与主线程的布尔变量同步，控制是否开始计时
        :param kwargs: 其他属性设置
        """
        super().__init__(master, **kwargs)
        self.boolVar = boolVar
        # test_time_var = tk.StringVar(value='0.000s')
        # self.timeVar = tk.StringVar(value='0.000s')
        self.config(textvariable=test_time_var)
        self.start = time.time()

        self.event = event
        self.test_time:float = 0.0

        self.boolVar.trace('w', self.test_time_event)

        t = threading.Thread(target=self.thread_time, daemon=True)
        t.start()

    def thread_time(self):
        # self.config(text='0.000s')
        while True:   # 通过这个释放线程
            if self.boolVar.get():      # 开始计时
                self.test_time = round(time.time() - self.start, 3)
                test_time_var.set(str(self.test_time)+'s')
                time.sleep(0.1)
            else:                       # 停止
                # 记录测试时间
                # print('线程将进入等待')
                # self.event.clear()
                self.event.wait(10000)           # 线程休眠，直到被主程序唤醒
                self.start = time.time()        # 重新获取开始的时间
                # print('线程启动')

    def test_time_event(self, *args):
        flag = self.boolVar.get()
        if flag:
            self.event.set()
        else:
            self.event.clear()